package com.example.config;


import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerConfig {

    private static int port = 8002;

    ServerConfig() {
        init();
    }

    private void init() {
        EventLoopGroup groupA = new NioEventLoopGroup(1);
        EventLoopGroup groupB = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(groupA, groupB)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128) //初始化服务端可连接队列,指定了队列的大小128
                .childOption(ChannelOption.SO_KEEPALIVE, true) //保持长连接
                .childHandler(new ChannelInitializer<SocketChannel>() {  // 绑定客户端连接时候触发操作
                    @Override
                    protected void initChannel(SocketChannel sh) throws Exception {
//                        sh.pipeline()
//                                .addLast(new RpcDecoder(RpcRequest.class)) //解码request
//                                .addLast(new RpcEncoder(RpcResponse.class)) //编码response
//                                .addLast(new ServerHandler()); //使用ServerHandler类来处理接收到的消息

                    }
                });

        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            if (future.isSuccess()) {
                System.out.println("服务器启动成功！");
                //成功绑定到端口之后,给channel增加一个 管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程。
                future.channel().closeFuture().sync();
            } else {
                System.out.println("服务端启动失败");
                future.cause().printStackTrace();
                groupA.shutdownGracefully(); //关闭线程组
                groupB.shutdownGracefully();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
